<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HeatMap D3</title>
    <script src="https://d3js.org/d3.v6.min.js"></script>
    <script src="heatmap.js"></script>
    <style>
    .container {
        position: relative;
    }

    #heatmap {
        position: absolute;
        top: 9;
        left: 9;
        z-index: 1; /* 这使得SVG层位于图像层之上 */
    }
    </style>
</head>
<body>
    <div class=".container">
        <img id="computershelf" src="images/rittal_part2.png" alt="Computer Shelf">
        <svg id="heatmap" width="0" height="0"></svg>
        <button id="changeBtn">change color</button>
    </div>
</body>
<script>
    const imgElement = document.getElementById('computershelf');
    const svgElement = d3.select('#heatmap');
    const grain = 4;
    const gradient = 0.009;
    const opacity = 0.7;

    // 等待图片加载完成
    imgElement.onload = function() {
        const width = imgElement.width;
        const height = imgElement.height;

        svgElement.attr('width', width).attr('height', height);

        // 初始化热力图
        const points = [
            { x: 50, y: 40, temp: 1 },
            { x: 104, y: 22, temp: 0.87 },
        ];
        initHeatmap(width, height, points);
    }

    function initHeatmap(width, height, points) {
        // 计算热点数据
        const heatData = generateHeatData(points, 0, 0, width, height, gradient, grain, opacity);

        // 定义颜色插值器
        const greenToYellow = d3.interpolateRgb("green", "yellow");
        const yellowToRed = d3.interpolateRgb("yellow", "red");

        // 定义颜色比例尺
        const colorScale = d3.scaleSequential(d => {
            return d <= 0.5 ? greenToYellow(d * 2) : yellowToRed((d - 0.5) * 2);
        }).domain([0, 1]);

        // 清空svg
        svgElement.selectAll('*').remove();

        // 创建圆圈表示热点
        const rects = svgElement.selectAll('rect')
                                .data(heatData)
                                .enter()
                                .append('rect');

        // 设置矩形属性
        rects.attr('x', d => d.x - Math.floor(grain / 2)) // 减去一半的边长使矩形居中
                .attr('y', d => d.y - Math.floor(grain / 2))
                .attr('width', grain) // 正方形的宽度
                .attr('height', grain) // 正方形的高度
                .style('fill', d => colorScale(d.intensity))
                .style('opacity', d => d.opacity);
    }

    var button = document.getElementById('changeBtn');

    // 添加点击事件监听器
    button.addEventListener('click', function(event) {
        const width = imgElement.width;
        const height = imgElement.height;

        const points = [];
        initHeatmap(width, height, points);
    });
</script>
</html>